package com.zcc.makingfriend.service.impl;

import com.zcc.makingfriend.dao.Chat;
import com.zcc.makingfriend.mapper.ChatMapper;
import com.zcc.makingfriend.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author zcc
 */
@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    ChatMapper chatMapper;

    @Override
    public int sendMessage(Chat chat) {
        chat.setTime(LocalDateTime.now());
        chat.setIsRead(0);
        return chatMapper.sendMessage(chat);
    }

    @Override
    public List<Chat> findChats(Chat chat) {
        List<Chat> chats1 = chatMapper.findChats(chat);
        List<Chat> chats = new ArrayList<>(chats1);
        List<Chat> chats2 = chatMapper.findChats(new Chat(chat.getOtherUuid(), chat.getMyUuid()));
        chats.addAll(chats2);
        chats.sort(Comparator.comparing(Chat::getTime));
        return chats;
    }

    @Override
    public int readChat(Chat chat) {
        Chat chat1 = new Chat(chat.getOtherUuid(), chat.getMyUuid());
        Chat chat2 = new Chat(chat.getMyUuid(), chat.getOtherUuid());
        int i = chatMapper.readChat(chat1);
        int j = chatMapper.readChat(chat2);
        return i > 0 && j > 0 ? 1 : 0;
    }

}
